package com.tonny.tweet.controller;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tonny.tweet.model.Tweet;
import com.tonny.tweet.model.User;
import com.tonny.tweet.service.TweetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/tweet")
public class TweetController extends BaseController {
    
    @Autowired
    private TweetService tweetService;
    
    @RequestMapping(value = "/")
    public String page() {
        return "main";
    }
    
    @RequestMapping(value = "/publish", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    @ResponseBody
    public String publish(@RequestBody JSONObject params) {
        Object user = getSession().getAttribute("user");
        if (user == null) {
            return "login";
        }
    
        Tweet tweet = tweetService.publish(((User) user).getId(), params.getString("content"));
        return "success";
    }
    
    @RequestMapping(value = "/delete/{tweetId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    @ResponseBody
    public String delete(@PathVariable long tweetId) {
        Object user = getSession().getAttribute("user");
        if (user == null) {
            return "login";
        }
        boolean deleted = tweetService.delete(((User) user).getId(), tweetId);
        return Boolean.toString(deleted);
    }
    
    @RequestMapping(value = "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    @ResponseBody
    public String pageList() {
        Object user = getSession().getAttribute("user");
        if (user == null) {
            return "login";
        }
        List<Tweet> tweets = tweetService.allMyTweet(((User) user).getId());
        return JSON.toJSONString(tweets);
    }
    
}
